<template>
	<view class="tabContent" v-show="true">
		<view class="param-title">基本信息</view>
		<view class="param-item">
			<label>姓名</label>
			<text class="text">{{ userInfo.name }}</text>
		</view>
		<view class="param-item">
			<label>年级</label>
			<button @click="openGradeTermPopup" class='button' plain="true">
				{{ userInfo.grade }}</button>
		</view>
		<vk-data-goods-sku-popup ref="skuPopup" v-model="gradeTermPopupData.show" border-radius="20" :z-index="990"
			:localdata="gradeGoodsInfo" :selected-init="true" :default-select="defaultSku"
			:mode="gradeTermPopupData.mode" :theme="gradeTermPopupData.theme" :show-close="gradeTermPopupData.showClose"
			:hide-stock="gradeTermPopupData.hideStock" :mask-close-able="gradeTermPopupData.maskCloseAble"
			@open="onOpenGradeTermPopup" @close="onCloseGradeTermPopup"
			@add-cart="confirmGradeTermSelection"></vk-data-goods-sku-popup>

		<view class="paramBox">
			<view class="param-title">考试信息</view>
			<view class="param-item">
				<label>考试名称</label>
				<uni-easyinput prefixIcon="chat-filled" :inputBorder='false' v-model="examRecord.examName"
					:placeholderStyle="placeholderStyle" placeholder='请输入考试名称' @input="handleExamNameChange">
				</uni-easyinput>
			</view>
			<view class="param-item">
				<label>考试日期</label>
				<picker mode="date" :value="examRecord.examDate" @change="handleExamDateChange" class="picker">
					<text class="text">{{ examRecord.examDate }}</text>
				</picker>
			</view>

			<!-- 根据年级获取对应的科目列表并循环展示科目输入框，添加key绑定，确保唯一性和高效更新 -->
			<view v-for="(subject, subjectIndex) in subjectList" :key="subjectIndex">
				<view class="param-item-2">
					<view class="item-2">
						<label>{{ subject.name }}</label>
						<uni-easyinput :inputBorder='false' :value="examRecord.scoreList[subjectIndex].score"
							type="digit" maxlength="4" :styles="{color: '#2979FF',}" placeholder='请输入分数'
							@input="handleSubjectScoreChange($event, subject, subjectIndex)">
						</uni-easyinput>
					</view>
					<view class="item-2">
						<label>满分</label>
						<text>{{subject.full}}</text>
					</view>
				</view>
			</view>

			<view class="param-title">排名信息</view>
			<view class="param-item">
				<label>班级排名</label>
				<uni-easyinput prefixIcon="hand-up-filled" :inputBorder='false' v-model="examRecord.class_rank"
					type="number" maxlength="3" :placeholderStyle="placeholderStyle" placeholder='请输入班级排名'
					@input="handleClassRankChange">
				</uni-easyinput>
			</view>
			<view class="param-item">
				<label>学校排名</label>
				<uni-easyinput prefixIcon="hand-up-filled" :inputBorder='false' v-model="examRecord.school_rank"
					type="number" maxlength="4" :placeholderStyle="placeholderStyle" placeholder='请输入学校排名'
					@input="handleSchoolRankChange">
				</uni-easyinput>
			</view>
		</view>
		<!-- 隔离与按钮直接的间隔 -->
		<view style="height: 30rpx;"></view>
		<view>
			<button type="primary" @click="saveStudentInfo">保存</button>
		</view>
	</view>
</template>

<script>
	import {
		reactive,
		onMounted,
		watch,
		toRefs
	} from 'vue';
	import {
		onShow,
		onLoad
	} from '@dcloudio/uni-app';
	import vkDataGoodsSkuPopup
	from '@/components/vk-data-goods-sku-popup/vk-data-goods-sku-popup.vue';
	import moment from 'moment';
	import {
		default_grade_subject,
		default_stage_grade
	} from '@/utils/enum';

	import _ from 'lodash'; // 引入lodash库，用于深拷贝等操作，在UPDATE_STUDENT等mutation中有用到

	// 在这里将gradeSubjectMap提升为全局变量，初始化为一个空的Map
	const gradeSubjectMap = new Map();

	export default {
		components: {
			vkDataGoodsSkuPopup
		},
		setup() {
			const db_student = uniCloud.importObject("db_student");
			const db_exam = uniCloud.importObject("db_exam");
			const placeholderStyle = "color:#000000;font-size:14px;font-weight:546;";
			const gradeList = default_stage_grade;
			// 响应式数据
			const state = reactive({
				userInfo: {},
				examRecord: {
					student_id: '',
					grade_name: '',
					exam_name: '',
					exam_date: moment().format('YYYY-MM-DD'),
					class_rank: '',
					school_rank: '',
					score_list: [],
				},
				gradeGoodsInfo: {},
				gradeTermPopupData: {
					show: false,
					goods_id: "001",
					theme: "default",
					showClose: true,
					maskCloseAble: false,
				},
				defaultSku: {
					sku: []
				},
				subjectList: []
			});

			// 处理考试名称输入变化
			const handleExamNameChange = (e) => {
				state.examRecord.examName = e;
			};

			// 处理考试日期选择变化
			const handleExamDateChange = (e) => {
				state.examRecord.examDate = e.detail.value;
			};

			// 打开年级学期选择弹窗
			const openGradeTermPopup = () => {
				state.gradeGoodsInfo = getGradeTermGoodsInfo(state.gradeTermPopupData.goods_id);
				if (!state.gradeGoodsInfo) {
					console.error('未获取到有效的年级学期商品信息');
					return;
				}
				state.gradeTermPopupData.show = true;
			};

			// 获取年级学期商品信息
			const getGradeTermGoodsInfo = (goodsId) => {
				return gradeList.find((item) => item._id === goodsId) || null;
			};

			// 年级学期选择弹窗打开时的监听方法
			const onOpenGradeTermPopup = () => {
				console.log("监听 - 打开年级学期选择组件");
			};

			// 年级学期选择弹窗关闭时的监听方法
			const onCloseGradeTermPopup = () => {
				console.log("监听 - 关闭年级学期选择组件");
			};

			// 年级学期选择确认后的逻辑处理
			const confirmGradeTermSelection = async (selectShop) => {
				console.log("监听 - 年级学期确认选择", selectShop);
				if (selectShop) {
					state.userInfo.grade = selectShop.goods_name
				}
				setTimeout(() => {
					state.gradeTermPopupData.show = false;
				}, 300);
			};

			// 从云端数据表中，根据年级获取对应的科目列表，用于展示
			const getSubjectList = async (grade) => {
				const subject_list = await db_exam.getSubjectList(grade);
				// 根据subject_list长度扩充score_list
				state.examRecord.scoreList = subject_list.map((subject) => ({
					score: 0,
					subject_id: subject.id,
					exam_record_id: subject.exam_record_id
				}));
				console.log('subject_list', subject_list);
				console.log('state.examRecord.scoreList', state.examRecord.scoreList);
				return subject_list;
			};

			// 根据年级更新考试信息中的科目列表数据
			const updateSubjectsByGrade = (grade) => {
				const subjects = getSubjectsByGrade(grade);
				state.examRecord.scoreList = subjects
				console.log('updateSubjectsByGrade scoreList', state.examRecord.scoreList)
			};

			// 处理科目分数输入变化
			const handleSubjectScoreChange = (e, subject, subjectIndex) => {
				const _scoreList = state.examRecord.scoreList
				const subjectScoreItem = _scoreList[subjectIndex];
				if (subjectScoreItem) {
					const inputScore = parseFloat(e);
					const fullScore = parseFloat(subject.full);
					if (isNaN(inputScore)) {
						return
					}
					if (!isNaN(fullScore) && inputScore >= 0 && inputScore <= fullScore) {
						subjectScoreItem.score = inputScore;
					} else {
						uni.showToast({
							title: `输入的${subjectScoreItem.name}分数超过满分${fullScore}，请输入有效数字`,
							icon: 'none', //'none' 表示只显示文字提示，也可其他图标如 'success'、'error'等
							duration: 3000 // 提示显示的时长，单位为毫秒，这里设置为 2 秒
						});
						subjectScoreItem.score = 0;
					}
					state.examRecord.scoreList[subjectIndex] = subjectScoreItem
				} else {
					console.warn(`未找到名为${subjectScoreItem.name}的科目对应的分数项，请检查数据`);
				}
			};

			// 处理科目满分输入变化
			const handleSubjectFullChange = (e, subjectIndex) => {
				const _subjects = state.examRecord.scoreList
				const subjectScoreItem = _subjects[subjectIndex];
				if (subjectScoreItem) {
					const inputFull = parseFloat(e);
					if (isNaN(inputFull)) {
						return
					}
					subjectScoreItem.full = e
				}
			};

			// 处理班级排名输入变化
			const handleClassRankChange = (e) => {
				const inputRank = parseInt(e);
				if (!isNaN(inputRank) && inputRank >= 0) {
					state.examRecord.class_rank = inputRank;
				} else {
					console.warn('输入的班级排名格式不正确，请输入有效数字');
					// 可以考虑将排名重置为合理的默认值等操作
				}
			};

			// 处理学校排名输入变化
			const handleSchoolRankChange = (e) => {
				const inputRank = parseInt(e);
				if (!isNaN(inputRank) && inputRank >= 0) {
					state.examRecord.school_rank = inputRank;
				} else {
					console.warn('输入的学校排名格式不正确，请输入有效数字');
					// 可以考虑将排名重置为合理的默认值等操作
				}
			};

			// 保存学生信息
			const saveStudentInfo = () => {
				const {
					examName,
					examDate,
					scoreList,
					class_rank,
					school_rank
				} = state.examRecord;
				if (!examName) {
					console.warn('考试名称不能为空');
					return;
				}
				if (!examDate) {
					console.warn('考试日期不能为空');
					return;
				}
				if (scoreList.some(s => s.score === '')) {
					console.warn('请填写所有科目的考试分数');
					return;
				}
				if (!class_rank) {
					console.warn('班级排名不能为空');
					return;
				}
				if (!school_rank) {
					console.warn('学校排名不能为空');
					return;
				}
				// 此处可以添加真正的保存逻辑，比如调用接口将数据发送到后端等
				console.log('数据校验通过，可进行保存操作，此处添加实际保存逻辑');
				// 构造新的考试信息对象
				const newExamInfo = {
					student_id: state.userInfo._id,
					grade_name: state.userInfo.grade,
					examName: examName,
					examDate: examDate,
					class_rank: parseInt(class_rank),
					school_rank: parseInt(school_rank),
					scoreList: scoreList
				};
				console.log('newExamInfo', newExamInfo);
				// // 调用updateExamInfo更新studentStore
				db_exam.updateExamRecord(newExamInfo);
			};

			// 在组件挂载完成时，调用updateSubjectsByGrade进行科目列表数据更新（传入初始的年级和学期数据）
			onMounted(() => {});

			//grade有变动，就会再次触发获取新的科目列表
			watch(() => state.userInfo.grade, async (newGrade) => {
				if (newGrade) {
					const subjectList = await getSubjectList(newGrade);
					state.subjectList = subjectList;
				}
			}, {
				immediate: true
			});

			// 在页面加载流程
			onLoad(async (options) => {
				console.log('进入onLoad生命周期钩子，准备加载用户信息，获取到的id值为：', options.id);
				// 调用云对象的getStudentInfo方法获取某一个学生的数据，主要获取grade年级信息和student _id，用于查找exam_record
				const studentData = await db_student.getStudentById(options.id);
				if (studentData) {
					state.userInfo = studentData;
					// 页面加载时，直接加载赋值gradeGoodsInfo，方便赋值defaultSku
					state.gradeGoodsInfo = getGradeTermGoodsInfo(state.gradeTermPopupData.goods_id);
					state.defaultSku.sku = state.gradeGoodsInfo['sku_list'].find((sku) => sku.goods_name ===
						state.userInfo.grade).sku_name_arr
				} else {
					console.error(`未找到id为${options.id}的学生信息`);
				}
				console.log('完成loadUserInfo调用');
				console.log('onLoad state.userInfo', state.userInfo)
				// 调用
			});


			return {
				...toRefs(state),
				gradeList,
				placeholderStyle,
				gradeSubjectMap,
				handleExamNameChange,
				handleExamDateChange,
				openGradeTermPopup,
				onOpenGradeTermPopup,
				onCloseGradeTermPopup,
				confirmGradeTermSelection,
				getSubjectList,
				updateSubjectsByGrade,
				handleSubjectScoreChange,
				handleSubjectFullChange,
				handleClassRankChange,
				handleSchoolRankChange,
				saveStudentInfo
			};
		}
	};
</script>

<style lang="scss" scoped>
	.tabContent {
		padding-top: 10rpx;
		background: #fff;
		overflow: hidden;
	}

	.param-title {
		background: #f5f5f5;
		height: 80rpx;
		line-height: 80rpx;
		margin: 10rpx 30rpx 0;
		font-size: 28rpx;
		text-indent: 30rpx;
	}

	.param-item {
		height: 80rpx;
		line-height: 80rpx;
		font-size: 28rpx;
		border-bottom: 1rpx solid #f5f5f5;
		border-left: 1rpx solid #f5f5f5;
		border-right: 1rpx solid #f5f5f5;
		margin: 0 30rpx;
		padding: 0 30rpx;
		display: flex;
	}

	.param-item label {
		width: 200rpx;
		color: #999;
	}

	.param-item-2 {
		width: 92%;
		display: flex;
		border-bottom: 1rpx solid #f5f5f5;
		border-left: 1rpx solid #f5f5f5;
		border-right: 1rpx solid #f5f5f5;
		margin-left: 30rpx;
	}

	.item-2 {
		width: 92%;
		height: 80rpx;
		line-height: 80rpx;
		font-size: 28rpx;
		margin-left: 30rpx;
		display: flex;
	}

	.item-2 label {
		margin-left: 30rpx;
		margin-right: 30rpx;
		color: #999;
	}

	.button {
		width: 85%;
		font-size: 28rpx;
		font-weight: 550;
		border-style: hidden;
		margin-right: 130rpx;
	}

	.text {
		font-size: 28rpx;
		font-weight: 550;
	}

	.picker {
		width: 100%;
		/* 设置宽度为整行宽度 */
		height: 80rpx;
		/* 可根据实际情况调整高度，保持和其他 param-item 一致 */
		line-height: 80rpx;
		font-size: 24rpx;
		display: flex;
		justify-content: flex-start;
		/* 将文本和展开图标两端对齐 */
		align-items: center;
		/* 垂直居中 */
		position: relative;
		/* 为了设置伪元素的定位 */
		padding-left: 110rpx;
	}

	.picker::after {
		content: "";
		position: absolute;
		right: 15rpx;
		/* 根据需要调整右侧距离，设置展开图标的位置 */
		top: 40%;
		width: 20rpx;
		height: 20rpx;
		border-top: 2rpx solid #999;
		border-right: 2rpx solid #999;
		transform: rotate(45deg);
	}
</style>